﻿namespace ECM7.Themes.Editor
{
	using System;
	using System.IO;
	using System.Windows.Forms;
	using Commons.Collections;
	using ECM7.Themes.Domain.Model;
	using ECM7.Themes.Domain.Model.Base;
	using ECM7.Themes.Domain.Services;

	using NVelocity.App;
	using NVelocity.Runtime;

	/// <summary>
	/// Основная форма приложения
	/// </summary>
	public partial class MainForm : Form
	{
		#region Инициализация

		/// <summary>
		/// Конструктор
		/// </summary>
		public MainForm()
		{
			try
			{
				InitializeComponent();
				AppSettings = new ApplicationSettings(Application.StartupPath);
				ConfigureVelocity(AppSettings);

				string configurationPath = Path.Combine(AppSettings.TemplatesPath, "configuration.json");

				config = JsonHelper.LoadFromFile<ThemeConfiguration>(configurationPath);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
				throw;
			}
		}

		/// <summary>
		/// Настройка движка для генерации файлов по шаблонам
		/// </summary>
		/// <param name="appSettings">Параметры приложения</param>
		private static void ConfigureVelocity(ApplicationSettings appSettings)
		{
			var props = new ExtendedProperties();
			props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, appSettings.TemplatesPath);
			props.AddProperty(RuntimeConstants.VM_LIBRARY, "global-macros.vm");

			// props.AddProperty(RuntimeConstants.VM_PERM_ALLOW_INLINE, true);
			// props.AddProperty(RuntimeConstants.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, true);
			// props.AddProperty(RuntimeConstants.VM_PERM_INLINE_LOCAL, false);
			// props.AddProperty(RuntimeConstants.VM_CONTEXT_LOCALSCOPE, true);
			Velocity.Init(props);
		}

		#endregion

		#region Свойства формы

		/// <summary>
		/// Настройки приложения
		/// </summary>
		public readonly ApplicationSettings AppSettings;

		/// <summary>
		/// Конфигурация шаблонов тем оформления
		/// </summary>
		private readonly ThemeConfiguration config;

		/// <summary>
		/// Текущая форма редактирования
		/// </summary>
		private ThemeEditorForm editForm;

		#endregion

		#region Пункты главного меню

		/// <summary>
		/// Пункт меню: Создать новоый проект
		/// </summary>
		private void MiCreateNewClick(object sender, EventArgs e)
		{
			// todo: закрывать текущую форму
			if (editForm != null)
			{
				editForm.Close();
			}

			ChooseTemplateForm chooseTemplateFormForm = new ChooseTemplateForm(config.Templates);

			if (chooseTemplateFormForm.ShowDialog(this) == DialogResult.OK)
			{
				editForm = new ThemeEditorForm(config, chooseTemplateFormForm.SelectedTemplateGuid, AppSettings)
				{
					MdiParent = this
				};

				editForm.Show();
			}
		}

		/// <summary>
		/// Пункт меню: Открыть проект
		/// </summary>
		private void MiOpenClick(object sender, EventArgs e)
		{
			OpenFileDialog openDialog = new OpenFileDialog();
			if (openDialog.ShowDialog() == DialogResult.OK)
			{
				UserData userData = JsonHelper.LoadFromFile<UserData>(openDialog.FileName);

				editForm = new ThemeEditorForm(config, userData, AppSettings)
				{
					MdiParent = this
				};

				editForm.Show();
			}
		}

		#endregion
	}
}
